package com.fingard.dsp.bank.directbank.ceb01;

import java.io.UnsupportedEncodingException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

import com.fingard.FGBiz;
import com.fingard.constant.Format;
import com.fingard.dsp.bank.directbank.DirectBase;
import com.fingard.net.WebRequest;
import com.fingard.text.StringHelper;
import com.fingard.util.TransIDHelper;
import com.fingard.xml.XmlTextWriter;


public class CEB01Base extends DirectBase {
	protected static final String INSERTSEQ = "INSERT INTO REQSEQIDMAPPING(URID,BANKCODE,TRANSDATE,REQSEQID,BANKREQSEQID) values (?,?,?,?,?);";
	protected static final String SELECTSEQ = "SELECT BANKREQSEQID FROM REQSEQIDMAPPING WHERE REQSEQID=? AND BANKCODE=?;";

	protected static TransIDHelper idHelper = new TransIDHelper(1,9999);
	
	protected void writeCommonHeaderBalTrans(XmlTextWriter xmlWriter, CEB01Header p_bankHeader) throws Exception{
		if(StringHelper.isNullOrEmpty(p_bankHeader.requestCode))
		{
			throw new Exception("未赋值接口代码requestCode");
		}
		if(StringHelper.isNullOrEmpty(p_bankHeader.transNodeName))
		{
			throw new Exception("未赋值交易报文节点名transaction");
		}
		if(StringHelper.isNullOrEmpty(p_bankHeader.transPatches))
		{
			throw new Exception("未赋值交易笔数transPatches");
		}
		if(StringHelper.isNullOrEmpty(p_bankHeader.batchID))
		{
			throw new Exception("未赋值批次号batchID");
		}
		
		xmlWriter.writeStartDocByDeclaration("<?xml version=\"1.0\" encoding=\""+getCharset()+"\"?>");
		xmlWriter.writeStartElement("transaction");
		xmlWriter.writeStartElement(p_bankHeader.transNodeName);
		xmlWriter.writeStartElement(p_bankHeader.transNodeName + "Request");
		xmlWriter.writeStartElement(p_bankHeader.transNodeName + "RequestHeader");
		xmlWriter.writeElementString("language", "zh-cn");
		Date timeNow = new Date();
		DateFormat tTimeFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		xmlWriter.writeElementString("clientTime", tTimeFormat.format(timeNow).replace(" ", "T"));
		
		xmlWriter.writeStartElement("logonPart");
		xmlWriter.writeElementString("userID", bankFront.org);
		xmlWriter.writeElementString("userPassword", bankFront.loginPasswd);
		xmlWriter.writeElementString("operatorID", bankFront.loginName);
		xmlWriter.writeEndElement();
		
		xmlWriter.writeElementString("batchID", p_bankHeader.batchID);
		xmlWriter.writeElementString("transPatches", p_bankHeader.transPatches);
		xmlWriter.writeEndElement();//end RequestHeader
	}
	
	/**光大第二批报文结构风格*/
	protected void writeCommonHeader_2(XmlTextWriter xmlWriter, CEB01Header p_bankHeader) throws Exception{
		if(StringHelper.isNullOrEmpty(p_bankHeader.TransCode))
		{
			throw new Exception("未赋值交易码TransCode");
		}
		
		if(StringHelper.isNullOrEmpty(p_bankHeader.batchID))
		{
			throw new Exception("未赋值交易流水号BatchID");
		}
		
		if(p_bankHeader.JnlDateTime == null)
		{
			throw new Exception("未赋值请求时间JnlDateTime");
		}
		
		xmlWriter.writeStartDocByDeclaration("<?xml version=\"1.0\" encoding=\""+getCharset()+"\"?>");
		xmlWriter.writeStartElement("Transaction");
		
		xmlWriter.writeStartElement("SystemHead");
		xmlWriter.writeElementString("Language", "zh_CN");
		xmlWriter.writeElementClosed("Encodeing");
		xmlWriter.writeElementClosed("Version");
		xmlWriter.writeElementClosed("ServiceName");
		xmlWriter.writeElementString("CifNo", bankFront.org);
		xmlWriter.writeElementString("UserID", bankFront.loginName);
		xmlWriter.writeElementClosed("SyMacFlag");
		xmlWriter.writeElementClosed("MAC");
		xmlWriter.writeElementClosed("SyPinFlag");
		xmlWriter.writeElementClosed("PinSeed");
		xmlWriter.writeElementClosed("LicenseId");
		xmlWriter.writeElementClosed("Flag");
		xmlWriter.writeElementClosed("Note");
		xmlWriter.writeEndElement();
		
		xmlWriter.writeStartElement("TransHead");
		xmlWriter.writeElementString("TransCode", p_bankHeader.TransCode);
		xmlWriter.writeElementString("BatchID", p_bankHeader.batchID);
		xmlWriter.writeElementString("JnlDate", Format.Date8Format.format(p_bankHeader.JnlDateTime));
		xmlWriter.writeElementString("JnlTime", Format.Time6Format.format(p_bankHeader.JnlDateTime));
		xmlWriter.writeEndElement();
		
	}
	
	protected String getBatchID(){
		return Format.DateTime12Year2Format.format(new Date())+idHelper.getNextIDStr();
	}
	
	protected String getCharset(){
		return getBankConfig().getCharset("GBK");
	}
	
	protected String[] sendToBank(String p_reqStr, String requestCode) throws UnsupportedEncodingException{
		String[] retStr = new String[]{"",""};
		String tmpUrl = "http://" + bankFront.serverIP + ":" + bankFront.serverPort + "/wangshangyh/banktrans/" + requestCode + "_request.xml?usrID=" + bankFront.org + "&userPassword=" + bankFront.loginPasswd + "&Sigdata=1";
        
        
        
        
        WriteBankLogLn("2.提交银行的地址：" + tmpUrl);
		WriteBankLogStep2(p_reqStr);
		WebRequest tmpWebRequest = new WebRequest(tmpUrl);
		tmpWebRequest.setConnectTimeout(100000);
		tmpWebRequest.setRequestProperty("Content-Type", "text/xml");
		tmpWebRequest.setRequestProperty("connection", "Close");
		
		byte[] tmpUpBytes = p_reqStr.getBytes(getCharset());
		retStr = tmpWebRequest.upload(tmpUpBytes, getCharset());
		
		//模拟返回
		//retStr[0]="";
		//retStr[1]=FileHelper.readFileText("D:\\Workspaces\\FilesForDevelop\\BankPort\\CEB01\\模拟用\\银行返回.xml", "gbk");
		//
		
		WriteBankLogStep3(retStr[1]);
		return retStr;
	}

	/**光大第二批报文结构，通讯*/
	protected String[] sendToBank_2Deposit(String p_reqStr, String p_transCode) throws UnsupportedEncodingException{
		String[] retStr = new String[]{"",""};
		String tmpUrl = "http://" + bankFront.serverIP + ":" + bankFront.serverPort + "/ent/" + p_transCode + ".do?userPassword="+ bankFront.loginPasswd + "&Sigdata=1";

		WriteBankLogLn("2.提交银行的地址：" + tmpUrl);
		WriteBankLogStep2(p_reqStr);
		WebRequest tmpWebRequest = new WebRequest(tmpUrl);
		tmpWebRequest.setConnectTimeout(100000);
		tmpWebRequest.setRequestProperty("Content-Type", "text/xml");
		tmpWebRequest.setRequestProperty("connection", "Close");

		byte[] tmpUpBytes = p_reqStr.getBytes(getCharset());
		retStr = tmpWebRequest.upload(tmpUpBytes, getCharset());

		//模拟返回
		//retStr[0]="";
		//retStr[1]=FileHelper.readFileText("D:\\zjbr-开发便捷小工具类\\xmlDealWith\\test.xml", "utf-8");

		WriteBankLogStep3(retStr[1]);
		return retStr;
	}

	/**光大第二批报文结构，通讯*/
	protected String[] sendToBank_2(String p_reqStr, String p_transCode) throws UnsupportedEncodingException{
		String[] retStr = new String[]{"",""};
		String tmpUrl = "http://" + bankFront.serverIP + ":" + bankFront.serverPort + "/ent/" + p_transCode + ".do?usrID=" + bankFront.org + "&userPassword="+ bankFront.loginPasswd + "&Sigdata=1";
        
        WriteBankLogLn("2.提交银行的地址：" + tmpUrl);
		WriteBankLogStep2(p_reqStr);
		WebRequest tmpWebRequest = new WebRequest(tmpUrl);
		tmpWebRequest.setConnectTimeout(100000);
		tmpWebRequest.setRequestProperty("Content-Type", "text/xml");
		tmpWebRequest.setRequestProperty("connection", "Close");
		
		byte[] tmpUpBytes = p_reqStr.getBytes(getCharset());
		retStr = tmpWebRequest.upload(tmpUpBytes, getCharset());
		
		//模拟返回
		//retStr[0]="";
		//retStr[1]=FileHelper.readFileText("D:\\Workspaces\\FilesForDevelop\\BankPort\\CEB01\\模拟用\\银行返回.xml", "gbk");
		//
		
		WriteBankLogStep3(retStr[1]);
		return retStr;
	}

    protected String[] sendToBankDownloadFile(String p_reqStr,String p_transCode, String fileName) throws UnsupportedEncodingException {
        String[] retStr = new String[]{"", ""};
        String tmpUrl = "http://" + bankFront.serverIP + ":" + bankFront.serverPort + "/ent/downloadFile.do?userPassword=" + bankFront.loginPasswd + "&transcode=" + p_transCode + "&fileName=" + fileName;

        WriteBankLogLn("2.提交银行的地址：" + tmpUrl);
        WebRequest tmpWebRequest = new WebRequest(tmpUrl);
        tmpWebRequest.setConnectTimeout(100000);
        tmpWebRequest.setRequestProperty("Content-Type", "text/xml");
        tmpWebRequest.setRequestProperty("connection", "Close");
        byte[] tmpUpBytes = p_reqStr.getBytes(getCharset());
        retStr = tmpWebRequest.upload(tmpUpBytes, getCharset());

        WriteBankLogStep3(retStr[1]);
        return retStr;
    }

    protected String[] sendToBankUploadFile(String p_transCode, String fileName,String clientPatchID) throws UnsupportedEncodingException {
        String[] retStr = new String[]{"", ""};
        String tmpUrl = "http://" + bankFront.serverIP + ":" + bankFront.serverPort + "/ent/uploadFile.do?userPassword=" + bankFront.loginPasswd + "&transcode=" + p_transCode + "&fileName=" + fileName + "&ClientPatchID=" + clientPatchID;

        WriteBankLogLn("2.提交银行的地址：" + tmpUrl);
        WebRequest tmpWebRequest = new WebRequest(tmpUrl);
        tmpWebRequest.setConnectTimeout(100000);
        tmpWebRequest.setRequestProperty("Content-Type", "text/xml");
        tmpWebRequest.setRequestProperty("connection", "Close");
        byte[] tmpUpBytes = "".getBytes(getCharset());
        retStr = tmpWebRequest.upload(tmpUpBytes, getCharset());

        WriteBankLogStep3(retStr[1]);
        return retStr;
    }

    //上送格式为json格式
    protected String[] sendToATS(String jsonData) throws Exception {
        String[] retStr = new String[]{"", ""};
        WriteBankLogLn("2.提交ATS的地址：" + FGBiz.dspCenter.dspSet.receiptPushServerUrl);

        //发送银行前置
        WebRequest tmpRequest = new WebRequest(FGBiz.dspCenter.dspSet.receiptPushServerUrl);
        tmpRequest.setConnectTimeout(10000);
        tmpRequest.setRequestProperty("connection", "Close");
        tmpRequest.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        String charsetName = getCharset();
        StringBuilder data = new StringBuilder();
        data.append(jsonData);
        WriteBankLogLn("3.推送给ATS的数据" + data.toString());
        byte[] tmpWriteBytes = data.toString().getBytes(charsetName);
        retStr = tmpRequest.upload(tmpWriteBytes, charsetName);
        WriteBankLogLn("4.返回的数据" + retStr[1]);

        return retStr;
    }

	/**
	 *  2  承兑 3  收票 4  撤票 10  背书转让 11  贴现 12  回购式贴现赎回 13  转贴现 14  回购式转贴现赎回
	 *  15  再贴现 16  回购式再贴现赎回 25  央行卖出商业汇票 17  保证 18  质押 19  质押解除
	 *  20  提示付款 21  逾期提示付款 22  追索 23  追索同意清偿
	 * @param title
	 * @return
	 */
	protected String getTransCodeToAts(String title){
		String transCode="";
		if("保证".equals(title)){
			transCode="17";
		}else if("转让背书".equals(title)){
			transCode="10";
		}else if("提示付款".equals(title)){
			transCode="20";
		}else if("质押背书".equals(title)){
			transCode="18";
		}else if("质押解除背书".equals(title)){
			transCode="19";
		}else if("买断式贴现背书".equals(title)){
			transCode="11";
		}
		return transCode;
	}
}
